<template>
  <el-dialog
    v-model="dialogVisible"
    title="订单发货"
    width="1200px"
    :before-close="handleClose"
  >

    <el-form ref="ruleForm" :model="formData" :rules="rules" label-position="right" size="small" class="delivery-form-inline" label-width="120px">

      <el-row>

        <el-col :span="12">
          <el-form-item label="发货日期：" prop="deliveryTime">
            <date-picker v-model:date="formData.deliveryTime" style="width: 100%" placeholder="请选择发货日期" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="发货人：" prop="deliveryUserId">
            <el-select v-model="formData.deliveryUserId" placeholder="请选择发货人" @change="headChange">
              <el-option
                v-for="item in headOptions"
                :key="item.id"
                :label="item.realName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="配送物流：" prop="logistics">
            <el-select v-model="formData.logistics" placeholder="请选择配送物流">
              <el-option
                v-for="item in logisticsOptions"
                :key="item.id"
                :label="item.realName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="物流单号：" prop="logisticsNo">
            <el-input
              v-model="formData.logisticsNo"
              placeholder="请输入物流单号"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="随货清单：">

            <el-checkbox-group v-model="formData.checkList" @change="checkboxChange">
              <el-checkbox v-for="(item,index) in goodsList" :key="index" :label="item.value">{{ item.label }}</el-checkbox>
            </el-checkbox-group>

          </el-form-item>
        </el-col>

      </el-row>
    </el-form>

    <item-title title="发货产品明细" />

    <el-table
      max-height="350"
      border
      :data="tableData"
    >
      <el-table-column type="index" width="55" />
      <el-table-column header-align="center" align="center" label="产品通用名">
        <template #default="scope">
          <el-select v-model="scope.row.productId" placeholder="请选择产品" @change="(val)=>{productChange(scope,val)}">
            <el-option
              v-for="item in products"
              :key="item.productId"
              :label="item.productPopularName"
              :value="item.productId"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column header-align="center" align="center" label="商品名" prop="productName" />
      <el-table-column header-align="center" align="center" label="包装规格" prop="packSpecs" />
      <el-table-column header-align="center" align="center" label="下单数量" prop="putNumber" width="130">
        <template #default="scope">
          <span v-if="scope.row.putNumber">{{ scope.row.putNumber }}/{{ getLabel('sell_unit',scope.row.sellUnit) }}</span>
        </template>
      </el-table-column>
      <el-table-column header-align="center" align="center" label="已发货数量" width="130">
        <template #default="scope">
          <span v-if="scope.row.delivery_number">{{ scope.row.delivery_number }}/{{ getLabel('sell_unit',scope.row.sellUnit) }}</span>

        </template>
      </el-table-column>
      <el-table-column header-align="center" align="center" label="批号">
        <template #default="scope">
          <el-input v-model="scope.row.batchNumber" clearable placeholder="请输入批号" />
        </template>
      </el-table-column>
      <el-table-column header-align="center" align="center" label="本次发货数量">
        <template #default="scope">
          <el-input v-model.number="scope.row.deliveryNumber" clearable placeholder="请输入数量" @blur="onBlur(scope)">
            <template #append>
              <span>{{ getLabel('sell_unit',scope.row.sellUnit) }}</span>
            </template>
          </el-input>
        </template>
      </el-table-column>
      <el-table-column header-align="center" align="center" label="操作" width="100">
        <template #default="scope">
          <el-button v-if="scope.$index != tableData.length - 1" type="text" @click.stop="onRemove(scope.row)">移除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="dialogConfirm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {crmStore} from '@CRM/store'
import {defineComponent, getCurrentInstance, inject, onBeforeMount, reactive, ref, toRefs} from 'vue'

export default defineComponent({
  name: 'DeliveryDialog2',
  setup(props, { emit }) {
    const currentInstance = getCurrentInstance()
    const api = inject('api')
    const goodsList = crmStore.getters['dictionary/getDictionary']['goods_list']
    const rules = ref({
      deliveryTime: [
        {
          type: 'date',
          required: true,
          message: '请选择发货日期',
          trigger: 'change',
        },
      ],
      deliveryUserId: [
        {
          required: true,
          message: '请选择发货人',
          trigger: 'change',
        },
      ],
      logistics: [
        {
          required: true,
          message: '请选择配送物流',
          trigger: 'change',
        },
      ],
      logisticsNo: [
        {
          required: true,
          message: '请输入物流单号',
          trigger: 'blur',
        },
      ]
    })

    var data = reactive({
      dialogVisible: false,
      selects: [],
      tableData: [],
      formData: {
        orderId: '',
        deliveryUserId: '',
        deliveryUserName: '',
        logistics: '神通',
        logisticsNo: '',
        accompanyingList: '',
        deliveryTime: '',
        checkList: []
      },
      headOptions: crmStore.getters['company/getHeadOptions'],
      logisticsOptions: [],
      products: [],
      ruleForm: null,
      datas: {}
    })

    const openDialog = (order) => {
      data.datas = { ...order }
      data.formData = {
        orderId: order.order.id,
        deliveryUserId: '',
        deliveryUserName: '',
        logistics: '神通',
        logisticsNo: '',
        accompanyingList: '',
        deliveryTime: '',
        checkList: []
      }
      data.datas.orderDetail.forEach(item => {
        item.delivery_number = 0
        item.total = 0
      })
      // data.tableData = data.datas.orderDetail
      data.tableData = [
        {
          productId: '',
          approvalNumber: '',
          packSpecs: '',
          putNumber: '',
          sellUnit: '',
          orderDetailId: '',
          batchNumber: '',
          deliveryNumber: '',
          delivery_number: '',
        }
      ]

      data.products = data.datas.orderDetail

      data.dialogVisible = true
    }

    const handleClose = () => {
      data.ruleForm.resetFields()
      data.ruleForm.clearValidate()
      data.dialogVisible = false
    }

    const checkboxChange = (val) => {
      console.log(val)
      console.log(val.join(','))
      data.formData.accompanyingList = val.join(',')
    }

    const onRemove = (scope) => {
      data.tableData.splice(scope.$index, 1)
    }

    const dialogConfirm = () => {
      data.ruleForm.validate((val) => {
        if (val) {
          const a = {
            delivery: data.formData,
            deliveryDetail: []
          }
          const list = []
          for (let i = 0; i < data.tableData.length; i++) {
            if (data.tableData[i].deliveryNumber) {
              if (!data.tableData[i].batchNumber) {
                currentInstance.proxy.customMessage({
                  type: 'error',
                  message: '请输入' + data.tableData[i].productPopularName + '的批号',
                })
                return
              } else {
                const b = {
                  orderDetailId: data.tableData[i].orderDetailId,
                  batchNumber: data.tableData[i].batchNumber,
                  deliveryNumber: data.tableData[i].deliveryNumber
                }
                list.push(b)
              }
            }
          }
          if (!list.length) {
            currentInstance.proxy.customMessage({
              type: 'error',
              message: '请输入需要发货产品的数量',
            })
            return
          }

          a.deliveryDetail = list

          api.order.ORDER_DELIVERY_CREATE(a).then(res => {
            if (!res.code) {
              currentInstance.proxy.customMessage({
                type: 'success',
                message: '操作成功',
              })

              emit('success')

              handleClose()
            }
          })
        }
      })
    }

    const handleSelectionChange = (val) => {
      data.selects = val
    }

    const headChange = (val) => {
      if (val) {
        const index = data.headOptions.findIndex(a => a.id == val)
        if (index != -1) {
          data.formData.deliveryUserName = data.headOptions[index].realName
        }
      } else {
        data.formData.deliveryUserName = ''
      }
    }

    const onBlur = (scope) => {
      let num = 0
      for (let i = 0; i < data.tableData.length; i++) {
        if (i != scope.$index) {
          if (data.tableData[i].orderDetailId == scope.row.orderDetailId) {
            num += data.tableData[i].deliveryNumber
          }
        }
      }

      if (scope.row.deliveryNumber > (scope.row.putNumber - num)) {
        scope.row.deliveryNumber = scope.row.putNumber - num
      }
    }

    const productChange = (scope, val) => {
      console.log(11111)
      if (val) {
        const index = data.products.findIndex(a => a.productId == val)
        if (index != -1) {
          const pro = data.products[index]
          console.log(data.tableData, scope.$index)
          const a = data.tableData[scope.$index]
          a.approvalNumber = pro.approvalNumber
          a.packSpecs = pro.packSpecs
          a.putNumber = pro.putNumber
          a.sellUnit = pro.sellUnit
          a.orderDetailId = pro.id
          a.batchNumber = ''
          a.deliveryNumber = 0
          a.delivery_number = pro.deliveryNumber
        }
      }
      if (scope.$index == data.tableData.length - 1) {
        data.tableData.push({
          productId: '',
          approvalNumber: '',
          packSpecs: '',
          putNumber: '',
          sellUnit: '',
          orderDetailId: '',
          batchNumber: '',
          deliveryNumber: '',
          delivery_number: '',
        })
      }
    }


    onBeforeMount(() => {
    })

    return {
      goodsList,
      ...toRefs(data),
      rules,

      openDialog,
      handleClose,
      dialogConfirm,
      handleSelectionChange,
      headChange,
      productChange,
      checkboxChange,
      onBlur,
      onRemove,
    }
  }
})
</script>

<style lang="scss" scoped>

    .delivery-form-inline{
        .el-form-item{
            .el-form-item__content{
                width: 100%;
                .el-select{
                    width: 100%;
                }
                .el-date-picker{
                    width: 100%;
                }
            }
        }
    }

</style>
